package com.sk.weichat.ui.me.redpacket;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ActivityOptions;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Bundle;
import android.support.constraint.ConstraintLayout;

import android.support.v4.app.ActivityCompat;
import android.support.v4.app.ActivityOptionsCompat;
import android.support.v4.util.Pair;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextPaint;
import android.text.TextUtils;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.transition.AutoTransition;
import android.transition.Explode;
import android.transition.Slide;
import android.transition.Transition;
import android.transition.TransitionInflater;
import android.transition.TransitionSet;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.widget.ImageView;
import android.widget.TextView;

import com.facebook.drawee.view.SimpleDraweeView;
import com.githang.statusbar.StatusBarCompat;
import com.sk.weichat.AppConstant;
import com.sk.weichat.R;
import com.sk.weichat.bean.RedpacketStatusBean;
import com.sk.weichat.bean.redpacket.EventRedReceivedStatus;
import com.sk.weichat.bean.redpacket.RedPacketNoticeBean;
import com.sk.weichat.bean.redpacket.RedpacketDetailBean;
import com.sk.weichat.helper.AvatarHelper;
import com.sk.weichat.helper.DialogHelper;
import com.sk.weichat.ui.WebAgreementActivity;
import com.sk.weichat.ui.base.BaseActivity;
import com.sk.weichat.ui.me.PersonalCenterActivity;
import com.sk.weichat.ui.tool.WebViewActivity;
import com.sk.weichat.util.Constants;
import com.sk.weichat.util.FrescoUtils;
import com.sk.weichat.util.ScreenUtil;
import com.sk.weichat.util.ToastUtil;
import com.xuan.xuanhttplibrary.okhttp.HttpUtils;
import com.xuan.xuanhttplibrary.okhttp.callback.BaseCallback;
import com.xuan.xuanhttplibrary.okhttp.result.ObjectResult;

import java.util.HashMap;
import java.util.Map;

import de.greenrobot.event.EventBus;
import okhttp3.Call;

import static android.view.Window.FEATURE_CONTENT_TRANSITIONS;
import static com.sk.weichat.bean.redpacket.RedpacketDetailBean.RedpacketDetailBean_Status_Key;
import static com.xuan.xuanhttplibrary.okhttp.result.Result.CODE_SUCCESS;

/**
 * @author lzs
 * @date 2019/10/10
 * Email:343067508@qq.com
 **/
public class RedPacketActivity extends BaseActivity {
    RedpacketDetailBean redPacketBean;

    static Map<Integer, String> statusMap = new HashMap<>();
    boolean isOwner;
    boolean isGroup;

    boolean isRandom;

    TextView tvUnAbleView;
    TextView tvUnableOpenTips;
    SimpleDraweeView ivAvatar;
    TextView tvContent;
    TextView tvName;
    TextView tvStatus;
    TextView tvRecord;
    //领
    ImageView ivOpen;
    //红包状态
    int status = -1;

    String extraID;

    static {
        statusMap.put(RedpacketDetailBean.Status_unopen, "");
        statusMap.put(RedpacketDetailBean.Status_empty, "红包已抢光");
        statusMap.put(RedpacketDetailBean.Status_refunded, "红包已过期");
        statusMap.put(RedpacketDetailBean.Status_opened, "");
        statusMap.put(RedpacketDetailBean.Status_expire, "红包记录无法查看了");
    }

    /**
     * @param context
     * @param redPacketBean 红包
     */
    public static final void startRedPacketActivity(Context context, RedpacketDetailBean redPacketBean, String extraID) {
        Intent intent = new Intent(context, RedPacketActivity.class);
        intent.putExtra("RedPacketBean", redPacketBean);
        intent.putExtra("extraID", extraID);
        context.startActivity(intent);
    }

//    public static final void startRedPacketActivityForResult(Activity context, RedpacketDetailBean redPacketBean, int requestCode) {
//        Intent intent = new Intent(context, RedPacketActivity.class);
//        intent.putExtra("RedPacketBean", redPacketBean);
//        context.startActivityForResult(intent, requestCode);
//    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
//            getWindow().requestFeature(FEATURE_CONTENT_TRANSITIONS);
//        }
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_redpacket2);

        //浅色状态栏字体图标
        StatusBarCompat.setLightStatusBar(getWindow(), false);
        ImageView ivBack = findViewById(R.id.iv_back);
        ConstraintLayout.LayoutParams lp = (ConstraintLayout.LayoutParams) ivBack.getLayoutParams();
        lp.topMargin += ScreenUtil.getStatusHeight(mContext);
        ivBack.setLayoutParams(lp);
        ivBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        redPacketBean = getIntent() != null ? getIntent().getParcelableExtra("RedPacketBean") : null;

        extraID = getIntent() != null ? getIntent().getStringExtra("extraID") : "";
        tvUnAbleView = findViewById(R.id.tv_unable_view);
        tvUnableOpenTips = findViewById(R.id.tv_unable_open_tips);
        ivAvatar = findViewById(R.id.iv_avatar);
        //红包内容
        tvContent = findViewById(R.id.tv_content);
        tvName = findViewById(R.id.tv_name);
        tvStatus = findViewById(R.id.tv_status);
        tvRecord = findViewById(R.id.tv_record);
        ivOpen = findViewById(R.id.iv_get);

        if (redPacketBean != null) {
            status = redPacketBean.getStatus();
            //发红包者id
            String fromId = String.valueOf(redPacketBean.getUserId());
            //当前用户是否是发送者
            isOwner = fromId.equals(coreManager.getSelf().getUserId());
            //是否群聊
            isGroup = !TextUtils.isEmpty(redPacketBean.getRoomId());
            // 是否拼手气红包
            isRandom = redPacketBean.getType() == RedpacketDetailBean.type_random;

            //Log.e("lzs", "isOwner:" + isOwner + "  isGroup:" + isGroup + "  isOpened:" + isOpened + "  isRandom:" + isRandom + "  status:" + status);
            setAvatar();
            setFromUserName();
            setGetButton();
            setStatus();
            setTips();
            setContent();
            setUnAbleReason();
            setContract();
        }
        setMoreAction();
    }

    private void goToWeb(String url) {
        Intent intent = new Intent(mContext, WebAgreementActivity.class);
        intent.putExtra("url", url);
        startActivity(intent);
    }

    //设置头像
    private void setAvatar() {
        if (!isGroup && !isOwner && status == RedpacketDetailBean.Status_unopen || !isGroup && !isOwner && status == RedpacketDetailBean.Status_refunded || isRandom && isOwner && status == RedpacketDetailBean.Status_unopen || isRandom && !isOwner && status == RedpacketDetailBean.Status_unopen ||
                !isRandom && isGroup && !isOwner && redPacketBean.getStatus() == RedpacketDetailBean.Status_unopen || !isOwner && !isRandom && isGroup && status == RedpacketDetailBean.Status_empty || !isOwner && !isRandom && isGroup && status == RedpacketDetailBean.Status_refunded) {
            ivAvatar.setVisibility(View.VISIBLE);
            FrescoUtils.loadImage(ivAvatar, AvatarHelper.getAvatarUrl(redPacketBean.getUserId() + "", true));
            ivAvatar.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    PersonalCenterActivity.start(mContext, redPacketBean.getUserId() + "");
                }
            });
        } else {
            ivAvatar.setVisibility(View.GONE);
        }
    }

    //设置发送者名称
    private void setFromUserName() {
        if (!isGroup && !isOwner && status == RedpacketDetailBean.Status_unopen || !isGroup && !isOwner && status == RedpacketDetailBean.Status_refunded || isRandom && isOwner && status == RedpacketDetailBean.Status_unopen || isRandom && !isOwner && status == RedpacketDetailBean.Status_unopen || !isOwner && !isRandom && isGroup && status == RedpacketDetailBean.Status_empty || !isOwner && !isRandom && isGroup && status == RedpacketDetailBean.Status_refunded||!isOwner && !isRandom && isGroup && status == RedpacketDetailBean.Status_unopen) {
            if (isRandom) {
                //拼手气红包，显示拼手气
                Drawable drawable = getResources().getDrawable(R.mipmap.icon_pin);
                drawable.setBounds(new Rect(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight()));
                tvName.setCompoundDrawables(null, null, drawable, null);
            }
            tvName.setText("来自 " + redPacketBean.getNickname() + " 的红包");
            tvName.setVisibility(View.VISIBLE);
        } else {
            tvName.setVisibility(View.GONE);
        }
    }

    //设置红包内容

    private void setContent() {
        if (!isGroup && !isOwner && status == RedpacketDetailBean.Status_unopen || !isGroup && !isOwner && status == RedpacketDetailBean.Status_refunded || isGroup && isRandom && status == RedpacketDetailBean.Status_unopen || isGroup && !isRandom && !isOwner && status == RedpacketDetailBean.Status_unopen || !isOwner && !isRandom && isGroup && status == RedpacketDetailBean.Status_empty || !isOwner && !isRandom && isGroup && status == RedpacketDetailBean.Status_refunded) {
            tvContent.setVisibility(View.VISIBLE);
            tvContent.setText(redPacketBean.getGreetings());
        } else {
            tvContent.setVisibility(View.GONE);
        }
    }

    private void setUnAbleReason() {
        if (isOwner && !isGroup) {
            if (status == RedpacketDetailBean.Status_unopen || status == RedpacketDetailBean.Status_opened || status == RedpacketDetailBean.Status_empty) {
                tvUnAbleView.setText(redPacketBean.getMoney() + "元红包已成功发给");
            } else if (redPacketBean.getStatus() == RedpacketDetailBean.Status_refunded) {
                tvUnAbleView.setText(redPacketBean.getMoney() + "元红包已过期");
            }
        }
        if (status == RedpacketDetailBean.Status_expire) {
            //过期72小时
            tvUnAbleView.setText("红包记录无法查看了");
        }
    }

    private void setTips() {
        if (isOwner && !isGroup) {
            tvUnableOpenTips.setVisibility(View.VISIBLE);
            if (status == RedpacketDetailBean.Status_unopen) {
                tvUnableOpenTips.setText("\"" + redPacketBean.getToUserName() + "\"" + "\n" + "有效期24小时");
            } else if (status == RedpacketDetailBean.Status_opened || status == RedpacketDetailBean.Status_empty) {
                tvUnableOpenTips.setText("\"" + redPacketBean.getToUserName() + "\"" + "\n" + "对方已领取");
            }
        } else {
            tvUnableOpenTips.setVisibility(View.INVISIBLE);
        }
    }

    //设置过期状态
    private void setStatus() {
        if (!isOwner && !isGroup && status != RedpacketDetailBean.Status_expire || isGroup && !isRandom && status != RedpacketDetailBean.Status_expire && !isOwner && (status == RedpacketDetailBean.Status_refunded || status == RedpacketDetailBean.Status_empty)) {
            tvStatus.setText(statusMap.get(status));
        } else {

        }
    }

    //设置领取按钮
    private void setGetButton() {
        if (!isOwner && !isGroup && status == RedpacketDetailBean.Status_unopen || isRandom && status == RedpacketDetailBean.Status_unopen || !isRandom && isGroup && !isOwner && status == RedpacketDetailBean.Status_unopen) {
            ivOpen.setVisibility(View.VISIBLE);
            ivOpen.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
//                    Intent intent = new Intent(mContext, PersonalRedPacketDetailsActivity.class);
//                    intent.putExtra(RedpacketDetailBean.RedpacketDetailBean_Key, redPacketBean);
//                    Pair<View, String> imagePair = Pair.create(ivAvatar, getString(R.string.radpacket_avatar_transition_name));
//                    ActivityCompat.startActivity(mContext, intent, ActivityOptionsCompat.makeSceneTransitionAnimation(RedPacketActivity.this, imagePair).toBundle());
                    // PersonalRedPacketDetailsActivity.startPersonalRedPacketDetailsActivityOptions(RedPacketActivity.this, redPacketBean, ActivityOptionsCompat.makeSceneTransitionAnimation(RedPacketActivity.this).toBundle());
//                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
//                        finishAfterTransition();
//                    } else {
//                        finish();
//                    }
                    openRedPacket(redPacketBean.getId());
                }
            });
        } else {
            ivOpen.setVisibility(View.GONE);
        }
    }

    //设置右上角按钮
    private void setMoreAction() {
        if (isRandom && !isOwner && status == RedpacketDetailBean.Status_unopen || isGroup && !isRandom && !isOwner && status == RedpacketDetailBean.Status_unopen) {
            tvRecord.setVisibility(View.GONE);
        } else {
            tvRecord.setVisibility(View.VISIBLE);
        }
        if (isOwner && isRandom && status == RedpacketDetailBean.Status_unopen) {
            //查看详情
            tvRecord.setText(getString(R.string.view_detail));
            tvRecord.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    //跳转红包详情
                    MucRedPacketDetailsActivity.startRedPacketDetailsActivity(mContext, redPacketBean);
                }
            });
        } else {
            //交易记录
            tvRecord.setText(getString(R.string.trade_record));
            tvRecord.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    //跳转交易记录
                    String url = coreManager.getConfig().TRADE_RECORDE + "?access_token=" + coreManager.getSelfStatus().accessToken + "&time=" + System.currentTimeMillis() / 1000;
                    WebViewActivity.start(mContext, url, false);
                }
            });
        }
    }

    /**
     * 设置协议
     */
    private void setContract() {
        if (status != RedpacketDetailBean.Status_unopen || status == RedpacketDetailBean.Status_unopen && isOwner && !isGroup) {
            return;
        }
        //钱包协议
        TextView tvContract = findViewById(R.id.tv_contract);

        SpannableString spannableString = new SpannableString(getString(R.string.redpacket_contract_of_wallet));
        ClickableSpan clickableSpan = new ClickableSpan() {
            @Override
            public void onClick(View widget) {
                goToWeb(coreManager.getConfig().WALLET_CONTRACT);
            }

            @Override
            public void updateDrawState(TextPaint ds) {
                super.updateDrawState(ds);
                ds.setColor(getResources().getColor(R.color.color_FFA889));
                ds.setUnderlineText(false);
                ds.clearShadowLayer();
            }
        };
        spannableString.setSpan(clickableSpan, 5, spannableString.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE);
        tvContract.setMovementMethod(LinkMovementMethod.getInstance());
        tvContract.setHighlightColor(Color.TRANSPARENT);
        tvContract.setText(spannableString);
        tvContract.setVisibility(View.VISIBLE);
    }


    /**
     * 打开红包
     */
    private void openRedPacket(String id) {
        DialogHelper.showDefaulteMessageProgressDialog(mContext);
        HashMap<String, String> params = new HashMap<String, String>();
        params.put("access_token", coreManager.getSelfStatus().accessToken);
        params.put("id", id);
        HttpUtils.get().url(coreManager.getConfig().REDPACKET_OPEN)
                .params(params)
                .build()
                .execute(new BaseCallback<RedpacketDetailBean>(RedpacketDetailBean.class) {

                    @SuppressLint("SetTextI18n")
                    @Override
                    public void onResponse(ObjectResult<RedpacketDetailBean> result) {
                        DialogHelper.dismissProgressDialog();
                        if (result.getResultCode() == CODE_SUCCESS) {
                            // Log.e("lzs", "领取成功 红包id:" + result.getData().getId() + "  status :" + result.getData().getStatus());
                            EventBus.getDefault().post(new EventRedReceivedStatus(extraID, result.getData().getStatus()));
                            if (!isRandom && !isOwner || !isGroup && !isOwner) {
                                // PersonalRedPacketDetailsActivity.startPersonalRedPacketDetailsActivityOptions(RedPacketActivity.this, result.getData(), ActivityOptionsCompat.makeSceneTransitionAnimation(RedPacketActivity.this).toBundle());
                                PersonalRedPacketDetailsActivity.startPersonalRedPacketDetailsActivity(mContext, result.getData());
                            } else {
                                //跳转
                                //MucRedPacketDetailsActivity.startRedPacketDetailsActivityOptions(mContext, result.getData(), ActivityOptionsCompat.makeSceneTransitionAnimation(RedPacketActivity.this).toBundle());
                                MucRedPacketDetailsActivity.startRedPacketDetailsActivity(mContext, result.getData());
                            }
                            finish();
                        } else if (result.getResultCode() == 1040329) {
                            //当日领取红包上限
                            tvContent.setVisibility(View.GONE);
                            tvName.setVisibility(View.GONE);
                            tvStatus.setVisibility(View.GONE);
                            ivAvatar.setVisibility(View.GONE);
                            ivOpen.setVisibility(View.GONE);
                            tvUnAbleView.setVisibility(View.VISIBLE);
                            tvUnableOpenTips.setVisibility(View.VISIBLE);
                            tvUnableOpenTips.setText(getResources().getString(R.string.tips_recieve_redpacket_exceed));
                            tvUnAbleView.setText(getResources().getString(R.string.recieve_redpacket_exceed));

                        } else {
                            ToastUtil.showToast(mContext, result.getResultMsg());
                        }
                    }

                    @Override
                    public void onError(Call call, Exception e) {
                        ToastUtil.showToast(mContext, getString(R.string.net_exception));
                        DialogHelper.dismissProgressDialog();
                    }
                });
    }
}
